package wwj;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

 



import wwj.entity.TupleEntity;
import wwj.entity.TupleEntity;
import wwj.reader.CsvReader;
import wwj.reader.TabReader;

/*
 *    hadoop jar /home/hadoop/桌面/boot.jar UsersMatrixParse2 /work/output/UsersMatrixParse1/4/part-r-00000  /work/output/UsersMatrixParse2/10

 */
public class UsersMatrixParse2 {

	public static class MMapper extends
			Mapper<Object, Text, TupleEntity,IntWritable  > {

		public void map(Object key, Text value, Context context)
				throws IOException, InterruptedException {
			List<String> list = TabReader
					.readLine(value.toString());
			TupleEntity entity=new TupleEntity();
			entity.setText1(list.get(0));
			entity.setText2(list.get(1));
			entity.setInt1(Integer.parseInt(list.get(2)));
			 context.write(entity, new IntWritable(Integer.parseInt(list.get(3))));
		}
	}

	public static class MReducer extends
			Reducer<TupleEntity, IntWritable, Text, DoubleWritable> {

		public void reduce(TupleEntity key, Iterable<IntWritable> values,
				Context context) throws IOException,
				InterruptedException {
			double q=key.getInt1().get();
			 
			for(IntWritable val:values){
				  
				 q=q*1.0/Math.sqrt(val.get());
			}
			 
			 context.write(new Text(key.getText1().toString()+"\t"+key.getText2().toString()  ),new DoubleWritable(q) );
			 
			

		}
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		String[] otherArgs = args;
		if (otherArgs.length < 2) {
			System.err.println("Usage:  <in> [<in>...] <out>");
			System.exit(2);
		}
		Job job = new Job(conf, "UsersMatrixParse2");
		job.setJarByClass(UsersMatrixParse2.class);
		 
		job.setMapperClass(MMapper.class);
		 
		job.setReducerClass(MReducer.class);
		job.setMapOutputKeyClass(TupleEntity.class);
		job.setMapOutputValueClass(IntWritable.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(DoubleWritable.class);
		for (int i = 0; i < otherArgs.length - 1; ++i) {
			FileInputFormat.addInputPath(job,
					new Path(otherArgs[i]));
		}
		FileOutputFormat.setOutputPath(job, new Path(
				otherArgs[otherArgs.length - 1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}
